/**

 @Name：layuiAdmin 主入口
 @Author：@@

 */

layui.extend({
  setter: 'config' //配置文件
  , admin: 'lib/admin' //核心模块
  , view: 'lib/view' //核心模块
}).define(['setter', 'admin'], function (exports) {
  // debugger
  var setter = layui.setter
      , element = layui.element
      , admin = layui.admin
      , tabsPage = admin.tabsPage
      , view = layui.view

      //根据路由渲染页面

      , renderPage = function () {
        var router = layui.router()
            , path = router.path
            // , path = router.href.split('/')
            , pathURL = admin.correctRouter(router.path.join('/'))
            , urlStr = layui.router().href
        //默认读取主页
        // debugger
        if (!path.length) path = [''];

        //如果最后一项为空字符，则读取默认文件
        if (path[path.length - 1] === '') {
          path[path.length - 1] = setter.entry;
        }

        /*
        layui.config({
          base: setter.base + 'controller/'
        });

        */
        // 校验是否过期
        // debugger
        // var current_time = new Date().getTime();
        // var first_time = layui.data('layuiAdmin').token_status
        // var val = (current_time - first_time) / 60000
        // if (val > 120) {
        //     layer.msg(
        //         '登录失效，请重新登录。'
        //     )
        //     // 重置初始时间状态
        //     layui.data('layuiAdmin', {
        //         key: "token_status",
        //         value: "timeout"
        //     })
        //     // debugger
        //     setTimeout(function () {
        //         if (window.debug) {
        //             window.location.href = 'http://10.0.23.97:8094/auth/oauth/authorize?response_type=token&client_id=client_1&redirect_uri=http://localhost:63342/XuChangFont/start/index.html?_ijt=r8gamlt0o96j6ai6l1hpsfut19#/home/home'
        //         } else {
        //             window.location.href = layui.setter.loginLocationHref
        //         }
        //     }, 2000);
        // }

        // 重置状态
        var reset = function (type) {
          //renderPage.haveInit && layer.closeAll();
          if (renderPage.haveInit) {
            $('.layui-layer').each(function () {
              var othis = $(this),
                  index = othis.attr('times');
              if (!othis.hasClass('layui-layim')) {
                layer.close(index);
              }
            });
          }
          renderPage.haveInit = true;
          $(APP_BODY).scrollTop(0);
          delete tabsPage.type; //重置页面标签的来源类型
        };
        // 如果路由来自于 tab 切换,或者关闭tag页，则不重新请求视图,
        if (tabsPage.type === 'tab') {
          // 切换到非主页、或者切换到主页且主页必须有内容。方可阻止请求
          if (pathURL !== '/' || (pathURL === '/' && admin.tabsBody().html())) {
            admin.tabsBodyChange(tabsPage.index);
            return reset(tabsPage.type);
          }
        }

        //请求视图渲染
        view().render(path.join('/')).then(function (res) {
          //遍历页签选项卡
          // debugger
          var matchTo
              , tabs = $('#LAY_app_tabsheader>li');

          tabs.each(function (index) {
            // var li = $(this)
            //   , layid = li.attr('lay-id');
            debugger;
            var li = $(this)
                , layAttr = li.attr('lay-attr')
                , layid = li.attr('lay-id');

            // if (layid === pathURL) {
            if (layAttr === urlStr && !window.createNewTagQC) {  // todo 判断当前,锚点和目标锚点
              matchTo = true; // 为True 的时候不打开新标签
              tabsPage.index = index;

            }
          });

          //如果未在选项卡中匹配到，则追加选项卡
          if (setter.pageTabs && pathURL !== '/') {
            // 获取当前url中的title参数
            debugger
            window.createNewTagQC = false  // 恢复标签页的状态,默认为false
            var titleStr = decodeURI(layui.router().search.title)
            if (!matchTo) {
              // window.createNewTagQC = false
              $(APP_BODY).append('<div class="layadmin-tabsbody-item layui-show"></div>');
              tabsPage.index = tabs.length;
              element.tabAdd(FILTER_TAB_TBAS, {
                // title: '<span>' + (res.title || "新选项卡") + '</span>'
                title: '<span>' + (res.title || titleStr) + '</span>'  // todo 通过锚点信息确定title
                // , id: pathURL
                , id: urlStr  // todo 通过锚点确定当前选项卡
                , attr: router.href
              });
            }
          }

          this.container = admin.tabsBody(tabsPage.index);
          setter.pageTabs || this.container.scrollTop(0); //如果不开启标签页，则跳转时重置滚动条
          //定位当前tabs
          // element.tabChange(FILTER_TAB_TBAS, pathURL); // layadmin-layout-tabs
          element.tabChange(FILTER_TAB_TBAS, urlStr); // layadmin-layout-tabs  // todo 通过锚点确定当前选项卡
          admin.tabsBodyChange(tabsPage.index);
        }).done(function () {
          layui.use('common', layui.cache.callback.common);
          $win.on('resize', layui.data.resize);

          element.render('breadcrumb', 'breadcrumb');

          //容器 scroll 事件，剔除吸附层
          admin.tabsBody(tabsPage.index).on('scroll', function () {
            var othis = $(this)
                , elemDate = $('.layui-laydate')
                , layerOpen = $('.layui-layer')[0];

            //关闭 layDate
            if (elemDate[0]) {
              elemDate.each(function () {
                var thisElemDate = $(this);
                thisElemDate.hasClass('layui-laydate-static') || thisElemDate.remove();
              });
              othis.find('input').blur();
            }

            //关闭 Tips 层
            layerOpen && layer.closeAll('tips');
          });
        });

        reset();
      }

      //入口页面
      , entryPage = function (fn) {

        var router = layui.router()
            , container = view(setter.container)
            , pathURL = admin.correctRouter(router.path.join('/'))
            , isIndPage;

        //检查是否属于独立页面
        layui.each(setter.indPage, function (index, item) {
          if (pathURL === item) {
            return isIndPage = true;
          }
        });

        //将模块根路径设置为 controller 目录
        layui.config({
          base: setter.base + 'controller/'
        });

        //独立页面
        if (isIndPage || pathURL === '/user/login') { //此处单独判断登入页，是为了兼容旧版（即未在 config.js 配置 indPage 的情况）
          container.render(router.path.join('/')).done(function () {
            admin.pageType = 'alone';
          });
        } else { //后台框架页面
          //强制拦截未登入
          if (setter.interceptor) {
            var local = layui.data(setter.tableName);
            // debugger
            if (!local[setter.request.tokenName]) {
              // todo 未登入跳转至oauth2接口
              // window.location.href = 'http://10.0.23.97:8094/auth/oauth/authorize?response_type=token&client_id=client_1&redirect_uri=http://www.baidu.com'
              if (window.debug) {
                window.location.href = 'http://10.0.23.97:8094/auth/oauth/authorize?response_type=token&client_id=client_1&redirect_uri=http://localhost:63342/ScProject/start/index.html?_ijt=r8gamlt0o96j6ai6l1hpsfut19#/home/home'
              } else {
                window.location.href = layui.setter.loginLocationHref //重新登录
              }
              return
            }
            //本地有token
            // debugger
            // if (layui.data('layuiAdmin').token_status == undefined || layui.data('layuiAdmin').token_status == 'timeout') { //取登录状态 如果是False
            //     var mytime = new Date();
            //     var first_login_time = mytime.getTime() // 第一次登陆进来的时间
            //     layui.data('layuiAdmin', {
            //         key: "token_status",
            //         value: first_login_time
            //     })
            //
            // }
          }

          //渲染后台结构
          if (admin.pageType === 'console') { //后台主体页
            renderPage();
          } else { //初始控制台结构
            container.render('layout').done(function () {
              renderPage();
              layui.element.render();

              if (admin.screen() < 2) {
                admin.sideFlexible();
              }
              admin.pageType = 'console';
            });
          }
        }
      }

      , APP_BODY = '#LAY_app_body', FILTER_TAB_TBAS = 'layadmin-layout-tabs'
      , $ = layui.$, $win = $(window);

  //初始主体结构
  layui.link(
      setter.base + 'style/admin.css?v=' + (admin.v + '-1')
      , function () {
        entryPage()
      }
      , 'layuiAdmin'
  );

  //监听Hash改变
  window.onhashchange = function () {
    entryPage();
    // debugger
    //执行 {setter.MOD_NAME}.hash 下的事件
    layui.event.call(this, setter.MOD_NAME, 'hash({*})', layui.router());
  };

  //扩展 lib 目录下的其它模块
  layui.each(setter.extend, function (index, item) {
    var mods = {};
    mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
    layui.extend(mods);
  });
  // 重置密码权限控制


  // 首页征管辅助提醒
  function getCurrentMonth() {
    var date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    if (month < 10) {
      month = "0" + month
    }
    return String(year) + String(month)
  }

  var currentMonth = getCurrentMonth()
  debugger
  admin.req({
    url: layui.setter.hostAddr + '/portal/appzgfz/getcount?ssyf=' + currentMonth
    , type: 'get'
    , async: false
    // , contentType: "application/json;charset=UTF-8"
    , success: function (msg) {
      // console.log('getcount请求成功')
      debugger
      var wcjqcCount = msg.wcjqcCount,
          jbflzCount = msg.jbflzCount,
          wcbqcCount = msg.wcbqcCount,
          sftxCount = msg.sftxCount,
          wdjfttxCount = msg.wdjfttxCount,
          cqzxtxCount = msg.cqzxtxCount,
          qszttxCount = msg.qszttxCount,
          fxfxtxCount = msg.fxfxtxCount,
          wsbqcCount = msg.wsbqcCount
      layui.data('layuiAdmin', {
        key: "indexTixing"
        , value: {
          wcjqcCount: wcjqcCount,
          jbflzCount: jbflzCount,
          wcbqcCount: wcbqcCount,
          sftxCount: sftxCount,
          wdjfttxCount: wdjfttxCount,
          cqzxtxCount: cqzxtxCount,
          qszttxCount: qszttxCount,
          fxfxtxCount: fxfxtxCount,
          wsbqcCount: wsbqcCount,
        }
      });

    }, error: function (err) {
      debugger
      doFail()
    }
  });
  if (layui.data('layuiAdmin').indexTixing.wcjqcCount === 0) {
    $("#wcjqcCountA").attr("disabled", true).css("pointer-events", "none");
    $("#wcjqcCount").css("color", "rgb(155,153,153)")
  } else {
    $("#wcjqcCount").html(layui.data('layuiAdmin').indexTixing.wcjqcCount)
    $("#wcjqcCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.jbflzCount === 0) {
    $("#jbflzCountA").attr("disabled", true).css("pointer-events", "none");
    $("#jbflzCount").css("color", "rgb(155,153,153)")
  } else {
    $("#jbflzCount").html(layui.data('layuiAdmin').indexTixing.jbflzCount)
    $("#jbflzCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.wcbqcCount === 0) {
    $("#wcbqcCountA").attr("disabled", true).css("pointer-events", "none");
    $("#wcbqcCount").css("color", "rgb(155,153,153)")
  } else {
    $("#wcbqcCount").html(layui.data('layuiAdmin').indexTixing.wcbqcCount)
    $("#wcbqcCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.sftxCount === 0) {
    $("#sftxCountA").attr("disabled", true).css("pointer-events", "none");
    $("#sftxCount").css("color", "rgb(155,153,153)")
  } else {
    $("#sftxCount").html(layui.data('layuiAdmin').indexTixing.sftxCount)
    $("#sftxCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.wdjfttxCount === 0) {
    $("#wdjfttxCountA").attr("disabled", true).css("pointer-events", "none");
    $("#wdjfttxCount").css("color", "rgb(155,153,153)")
  } else {
    $("#wdjfttxCount").html(layui.data('layuiAdmin').indexTixing.wdjfttxCount)
    $("#wdjfttxCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.cqzxtxCount === 0) {
    $("#cqzxtxCountA").attr("disabled", true).css("pointer-events", "none");
    $("#cqzxtxCount").css("color", "rgb(155,153,153)")
  } else {
    $("#cqzxtxCount").html(layui.data('layuiAdmin').indexTixing.cqzxtxCount)
    $("#cqzxtxCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.qszttxCount === 0) {
    $("#qszttxCountA").attr("disabled", true).css("pointer-events", "none");
    $("#qszttxCount").css("color", "rgb(155,153,153)")
  } else {
    $("#qszttxCount").html(layui.data('layuiAdmin').indexTixing.qszttxCount)
    $("#qszttxCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.fxfxtxCount === 0) {
    $("#fxfxtxCountA").attr("disabled", true).css("pointer-events", "none");
    $("#fxfxtxCount").css("color", "rgb(155,153,153)")
  } else {
    $("#fxfxtxCount").html(layui.data('layuiAdmin').indexTixing.fxfxtxCount)
    $("#fxfxtxCount").css("color", "#1E9FFF")
  }

  if (layui.data('layuiAdmin').indexTixing.wsbqcCount === 0) {
    $("#wsbqcCountA").attr("disabled", true).css("pointer-events", "none");
    $("#wsbqcCount").css("color", "rgb(155,153,153)")
  } else {
    $("#wsbqcCount").html(layui.data('layuiAdmin').indexTixing.wsbqcCount)
    $("#wsbqcCount").css("color", "#1E9FFF")
  }

  // 首页提醒赋值
  (function () {
    if (layui.data('layuiAdmin').indexTixing.wcjqcCount === 0) {
      $("#wcjqcCountA").attr("disabled", true).css("pointer-events", "none");
      $("#wcjqcCount").css("color", "rgb(155,153,153)")
    } else {
      $("#wcjqcCount").html(layui.data('layuiAdmin').indexTixing.wcjqcCount)
      $("#wcjqcCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.jbflzCount === 0) {
      $("#jbflzCountA").attr("disabled", true).css("pointer-events", "none");
      $("#jbflzCount").css("color", "rgb(155,153,153)")
    } else {
      $("#jbflzCount").html(layui.data('layuiAdmin').indexTixing.jbflzCount)
      $("#jbflzCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.wcbqcCount === 0) {
      $("#wcbqcCountA").attr("disabled", true).css("pointer-events", "none");
      $("#wcbqcCount").css("color", "rgb(155,153,153)")
    } else {
      $("#wcbqcCount").html(layui.data('layuiAdmin').indexTixing.wcbqcCount)
      $("#wcbqcCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.sftxCount === 0) {
      $("#sftxCountA").attr("disabled", true).css("pointer-events", "none");
      $("#sftxCount").css("color", "rgb(155,153,153)")
    } else {
      $("#sftxCount").html(layui.data('layuiAdmin').indexTixing.sftxCount)
      $("#sftxCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.wdjfttxCount === 0) {
      $("#wdjfttxCountA").attr("disabled", true).css("pointer-events", "none");
      $("#wdjfttxCount").css("color", "rgb(155,153,153)")
    } else {
      $("#wdjfttxCount").html(layui.data('layuiAdmin').indexTixing.wdjfttxCount)
      $("#wdjfttxCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.cqzxtxCount === 0) {
      $("#cqzxtxCountA").attr("disabled", true).css("pointer-events", "none");
      $("#cqzxtxCount").css("color", "rgb(155,153,153)")
    } else {
      $("#cqzxtxCount").html(layui.data('layuiAdmin').indexTixing.cqzxtxCount)
      $("#cqzxtxCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.qszttxCount === 0) {
      $("#qszttxCountA").attr("disabled", true).css("pointer-events", "none");
      $("#qszttxCount").css("color", "rgb(155,153,153)")
    } else {
      $("#qszttxCount").html(layui.data('layuiAdmin').indexTixing.qszttxCount)
      $("#qszttxCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.fxfxtxCount === 0) {
      $("#fxfxtxCountA").attr("disabled", true).css("pointer-events", "none");
      $("#fxfxtxCount").css("color", "rgb(155,153,153)")
    } else {
      $("#fxfxtxCount").html(layui.data('layuiAdmin').indexTixing.fxfxtxCount)
      $("#fxfxtxCount").css("color", "#1E9FFF")
    }

    if (layui.data('layuiAdmin').indexTixing.wsbqcCount === 0) {
      $("#wsbqcCountA").attr("disabled", true).css("pointer-events", "none");
      $("#wsbqcCount").css("color", "rgb(155,153,153)")
    } else {
      $("#wsbqcCount").html(layui.data('layuiAdmin').indexTixing.wsbqcCount)
      $("#wsbqcCount").css("color", "#1E9FFF")
    }
  })()


  //对外输出
  exports('index', {
    render: renderPage
  });
});
var currentMonth = getCurrentMonth()

// $.ajax({
//         url: layui.setter.hostAddr + '/portal/appzgfz/getcount?ssyf=' + currentMonth
//         // , data: JSON.stringify(obj.field)
//         , type: 'get'
//         , async: false
//         ,beforeSend: function (XMLHttpRequest) {
//                     XMLHttpRequest.setRequestHeader("Authorization", myAuthorization);
//                 }
//         // , contentType: "application/json;charset=UTF-8"
//         , success: function (msg) {
//             var wcjqcCount = msg.wcjqcCount,
//                 jbflzCount = msg.jbflzCount,
//                 wcbqcCount = msg.wcbqcCount,
//                 sftxCount = msg.sftxCount,
//                 wdjfttxCount = msg.wdjfttxCount,
//                 cqzxtxCount = msg.cqzxtxCount,
//                 qszttxCount = msg.qszttxCount,
//                 fxfxtxCount = msg.fxfxtxCount,
//                 wsbqcCount = msg.wsbqcCount
//
//             layui.data('layuiAdmin', {
//                 key: "indexTixing"
//                 , value: {
//                     wcjqcCount: wcjqcCount,
//                     jbflzCount: jbflzCount,
//                     wcbqcCount: wcbqcCount,
//                     sftxCount: sftxCount,
//                     wdjfttxCount: wdjfttxCount,
//                     cqzxtxCount: cqzxtxCount,
//                     qszttxCount: qszttxCount,
//                     fxfxtxCount: fxfxtxCount,
//                     wsbqcCount: wsbqcCount,
//                 }
//             });
//         }, error: function (err) {
//             doFail()
//         }
//     });

function getCurrentMonth() {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  if (month < 10) {
    month = "0" + month
  }
  return String(year) + String(month)
}